//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
const config=require('../config');
const HttpHelper = require('./httpHelper');
let accessToken='';
let updateAccessToken=async function(){
    let token=await HttpHelper.getLocal(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.weChat.appid}&secret=${config.weChat.appsecret}`);
    let tokenObj=JSON.parse(token);
    console.log('更新了token',tokenObj.access_token);
    accessToken=tokenObj.access_token;
};
if(!config.debug){
    updateAccessToken();
    setInterval(()=>{
        updateAccessToken();
    },7199000);
}
let weChat={
    msgSecCheck:async function(content){
        if(config.debug){
            return true;
        }
        let checkObj=await HttpHelper.postLocal(`https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${accessToken}`,{content:content});
        if(checkObj.errcode===40001){
            await updateAccessToken();
            checkObj=await HttpHelper.postLocal(`https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${accessToken}`,{content:content});
        }
        //let checkObj=JSON.parse(checkStr);
        return checkObj.errcode===0;
    }
};

// setTimeout(async function(){
//     console.log(await weChat.msgSecCheck('你好世界'));
// },3000)

module.exports=weChat;